Carbon

     

Turning Scheduling Off

In cases where you need to ensure data coherency, The Thread Manager provides a pair of functions, ThreadBeginCritical and ThreadEndCritical that disable scheduling temporarily by marking a section of code as critical. While the critical section of code is executing, no other threads can be scheduled; that is, the Thread Manager ignores all yield and other scheduling functions until the code exits the critical section.

Listing 5 shows a situation in which ThreadBeginCritical and ThreadEndCritical mark a section of code as critical.

Listing 5  Marking a critical section of code


Boolean batch = true
#define kNumOfPhilos                5   /* Number of icons to create*/
#define kNoCreationOptions          0   /* Use default options*/
#define kDefaultStackSize           0   /* System determines stack size */
            ...
void DoCreateThreads()
{
    OSErr anError;
    short index;
if batch ThreadBeginCritical();
    for ( index = 0; index < kNumOfPhilos; index++ )
    {
        anError = NewThread(kCooperativeThread, 
                                 DoPhiloActions, 
                                 (void *)&(gPhilo[index]),
                                 kDefaultStackSize,
                                 kNoCreationOptions, 
                                 nil,
                                 &(gPhilo[index].theThread);
        
        if ( anError )
            DoHandlerError("\pError in creating the New Thread
            (DoSpawnThreads)", anError, kFatal);
    YieldToAnyThread
    }
if batch ThreadEndCritical();

As you can see, the DoCreateThreads function calls the NewThread function in a loop to allocate a number of threads. In this case, the index for the for loop is the constant kNumOfPhilos , which is set to 5. So DoCreateThreads calls the NewThread function until it has created five new threads. If there is a problem allocating the threads, DoCreateThreads calls the error handling function and passes it the result code returned by NewThrea d.

In some cases you might want each newly created thread to run before the rest of the threads are created. However, in other cases, you might want DoCreateThreads to create all the threads before any of them runs. The Boolean variable batch and the ThreadBeginCritical and ThreadEndCritical functions enable you to control whether the threads begin running individually or together.

When batch is true, the code in the loop is marked as critical, so the Thread Manager ignores the YieldToAnyThread function. All the threads are created before any of them can run.

On the other hand, if batch is false, the loop is not marked as a critical section of code. The current thread yields control at the end of the loop, and since threads are created in the ready state, each newly created thread runs immediately after creation.

Working With Stacks


© 2000 Apple Computer, Inc. – (Last Updated 09 May 00)